package watermark;

import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class WatermarkUtils {
    private static String inputPath  = "C:\\Users\\wmz\\Desktop\\20220211164232510.docx";
    private static String inputPathToDocx  = "C:\\Users\\wmz\\Desktop\\20220211164232510.docx";
    private static String outPath  = "C:\\Users\\wmz\\Desktop\\20220211164232510_1.docx";
    private static String markStr = "理财有风险，投资需谨慎";

    public static void main(String[] args) {
        Map<String, Object> params = new HashMap<>();
        String type = inputPath.substring((inputPath.lastIndexOf(".") + 1));
        if ("doc".equals(type)) {
            docToDocx(inputPath,inputPathToDocx);
            setWordWaterMark(inputPathToDocx,outPath,markStr,params);
        } else if ("docx".equals(type)) {
            setWordWaterMark(inputPath, outPath, markStr,params);
        } else {
            System.out.println("格式有误！");
        }
    }

    /**
     * doc文档转docx
     * @param inPath doc原文件路径
     * @param outPath 转为docx的路径
     */
    public static void docToDocx(String inPath, String outPath) {
        try {
            File file = new File(outPath);
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(inPath);
            doc.save(os, SaveFormat.DOCX);// 这里可以写你想要装换的类型：DOC, DOCX, PDF，HTML
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置水印
     * @param inputPath 输入的docx路径
     * @param outPath 文件保存路径
     * @param markStr 水印内容
     * @param params 其他参数（预留传入其他参数，如透明度、颜色等等）
     */
    public static void setWordWaterMark(String inputPath, String outPath, String markStr, Map<String,Object> params) {
        File inputFile = new File(inputPath);
        XWPFDocument doc = null;
        try {
            // 延迟解析比率
            ZipSecureFile.setMinInflateRatio(-1.0d);
            doc = new XWPFDocument(new FileInputStream(inputFile));
        } catch (FileNotFoundException e) {
            System.out.println( "源文件不存在");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println( "读取源文件IO异常");
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println( "不支持的文档格式");
            e.printStackTrace();
        }
        org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy headerFooterPolicy = doc.getHeaderFooterPolicy();
        if (headerFooterPolicy == null) {
            headerFooterPolicy = doc.createHeaderFooterPolicy();
        }
        //添加水印
        headerFooterPolicy.createWatermark(markStr,params);

        File file = new File(outPath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                System.out.println( "创建输出文件失败");
                e.printStackTrace();
            }
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(outPath);
            doc.write(os);
        } catch (FileNotFoundException e) {
            System.out.println( "创建输出文件失败");
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println( "添加文档水印失败");
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (doc != null) {
                try {
                    doc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

